//
//  TS_addTabBar.swift
//  todaySwift
//
//  Created by ChokWah on 2018/3/6.
//  Copyright © 2018年 ChokWah. All rights reserved.
//

import UIKit

@objc protocol TS_TabBarDelegate : UITabBarDelegate {
    @objc func tabBarDidClickPlusButton(tabBar: TS_addTabBar)
}

class TS_addTabBar: UITabBar {
    var tdelegate: TS_TabBarDelegate?
    override init(frame: CGRect) {
        super.init(frame: frame) // 其实这里可以不用调用
        self.backgroundColor = UIColor.white
        self.addSubview(plusButton)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //
    private lazy var plusButton : UIButton = {
        let button = UIButton(type: .custom)
        button.setBackgroundImage( #imageLiteral(resourceName: "feed_publish_44x44_") , for: .normal)
        button.size = (button.currentBackgroundImage?.size)!
        button.addTarget(self, action: #selector(tabBarClickAction(tabBar:)), for: .touchUpInside)
//        button.sizeToFit()
        return button
    }()
    
    // 关键点
    override func layoutSubviews() {
        super.layoutSubviews()
        // 布局完然后覆盖
        
        // 设为中间
        plusButton.centerX = self.width/2
        // 突出的部分
        plusButton.y = -7
        
        // 把其他的tabbar设置好
        let tabbarW = self.width/5
        var tabbarIndex = 0
        for view in self.subviews {
            // 判断是否为非自定义tabbar
            if !view.isKind(of:NSClassFromString("UITabBarButton")!) { continue }
            view.width = tabbarW
            view.x = CGFloat(tabbarIndex) * tabbarW
            let buttonX = tabbarW * (tabbarIndex > 1 ? CGFloat(tabbarIndex + 1) : CGFloat(tabbarIndex))
            view.x = buttonX
            tabbarIndex += 1
        }
    }
    
    @objc func tabBarClickAction(tabBar: TS_addTabBar) {
        if (self.tdelegate?.responds(to: #selector(TS_TabBarDelegate.tabBarDidClickPlusButton(tabBar:))))! {
            self.tdelegate?.tabBarDidClickPlusButton(tabBar: self)
        }
    }
    

    

}
